package com.client.service.impl;

import com.Emplyment.dto.CommentDto;
import com.Emplyment.dto.InterViewDto;
import com.Emplyment.entity.Comment;
import com.Emplyment.entity.InterView;
import com.Emplyment.exception.BaseException;
import com.Emplyment.utils.SensitiveWordUtil;
import com.Emplyment.vo.CommentVo;
import com.Emplyment.vo.InterViewVo;
import com.client.mapper.InterViewMapper;
import com.client.service.InterViewService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class InterViewServiceImpl implements InterViewService {

    @Autowired
    private InterViewMapper interViewMapper;
    @Override
    public List<InterViewVo> getInterviews(String Category) {
        List<InterViewVo> interviews = interViewMapper.getInterviews(Category);
        return interviews;
    }

    @Override
    public List<CommentVo> getComments(List<Integer> interviewIds) {
        List<CommentVo> comments = interViewMapper.getComments(interviewIds);
        return comments;
    }

    @Override
    public void insertInterview(InterViewDto interview) {

        String content = interview.getContent();
        if(checkWord(content)){
            throw new BaseException("文章内容含有敏感词");
        }

        InterView interviewEntity = new InterView();
        BeanUtils.copyProperties(interview, interviewEntity);
        interviewEntity.setAuthor(interview.getUsername());
        interviewEntity.setUserPic(interview.getUserPic());
        interviewEntity.setTimestamp(LocalDateTime.now());
        Random rand = new Random();
        interviewEntity.setInterviewId(rand.nextInt(1000000));
        interViewMapper.insertInterview(interviewEntity);
    }

    @Override
    public void insertComment(CommentDto comment) {

        String newComment = comment.getNewComment();
        if(checkWord(newComment)){
            throw new BaseException("评论内容含有敏感词");
        }

        Comment commentEntity = new Comment();
        BeanUtils.copyProperties(comment, commentEntity);
        LocalDateTime time = LocalDateTime.now();
        commentEntity.setTimestamp(time);
        interViewMapper.insertComment(commentEntity);
    }

    public boolean checkWord(String content){
        boolean flag = false;
        List<String> words = interViewMapper.getWords();
        SensitiveWordUtil.initMap(words);
        Map<String, Integer> wordMap = SensitiveWordUtil.matchWords(content);
        if (wordMap.size() > 0){
            System.out.println("敏感词：" + wordMap);
            flag = true;
        }
        return flag;
    }

}
